from rest_framework import serializers
from .models import Asset, AssetCategory, Department, Location, User, Supplier, Contract

class AssetSerializer(serializers.ModelSerializer):
    """资产模型的序列化器"""
    # 使用 source 参数来获取关联对象的可读名称
    category_name = serializers.CharField(source='category.name', read_only=True)
    department_name = serializers.CharField(source='department.name', read_only=True)
    location_name = serializers.CharField(source='location.name', read_only=True)
    user_name = serializers.CharField(source='user.username', read_only=True)
    ledger_name = serializers.CharField(source='ledger.name', read_only=True)
    ledger_organization_id = serializers.IntegerField(source='ledger.organization_id', read_only=True)
    ledger_organization_name = serializers.CharField(source='ledger.organization.name', read_only=True)

    class Meta:
        model = Asset
        fields = [
            'id',
            'name',
            'asset_number',
            'status',
            'purchase_date',
            'purchase_price',
            'warranty_period',
            'description',
            'image',
            'qr_code',
            # 关联对象的ID，用于写入操作
            'category',
            'department',
            'location',
            'user',
            'ledger',
            # 只读的关联对象名称
            'category_name',
            'department_name',
            'location_name',
            'user_name',
            'ledger_name',
            'ledger_organization_id',
            'ledger_organization_name',
            'created_at',
            'updated_at',
        ]
        # 将关联字段设置为只在写入时需要，读取时使用上面的 *_name 字段
        extra_kwargs = {
            'category': {'write_only': True},
            'department': {'write_only': True, 'required': False, 'allow_null': True},
            'location': {'write_only': True, 'required': False, 'allow_null': True},
            'user': {'write_only': True, 'required': False, 'allow_null': True},
            'ledger': {'write_only': True, 'required': False, 'allow_null': True},
        }

class DepartmentSerializer(serializers.ModelSerializer):
    """部门模型的序列化器"""
    class Meta:
        model = Department
        fields = '__all__'

class LocationSerializer(serializers.ModelSerializer):
    """位置模型的序列化器"""
    class Meta:
        model = Location
        fields = '__all__'

class SupplierSerializer(serializers.ModelSerializer):
    """供应商模型的序列化器"""
    class Meta:
        model = Supplier
        fields = '__all__'

class ContractSerializer(serializers.ModelSerializer):
    """合同模型的序列化器"""
    class Meta:
        model = Contract
        fields = '__all__'
